package com.bbzn.device.client.service.emq.data;

import com.alibaba.fastjson.JSON;
import com.bbzn.device.client.dto.api.ResultResponse;
import com.bbzn.device.client.dto.api.position.GetPositionRequest;
import com.bbzn.device.client.dto.api.position.GetPositionResult;
import com.bbzn.device.client.dto.api.weatherInfo.GetWeatherInfoRequest;
import com.bbzn.device.client.dto.api.weatherInfo.GetWeatherInfoResult;
import com.bbzn.device.client.dto.api.weatherInfo.LiveInfo;
import com.bbzn.device.client.dto.ct.data.ProductUnionDTO;
import com.bbzn.device.client.dto.gps.GpsResult;
import com.bbzn.device.client.dto.position.WifiPosition;
import com.bbzn.device.client.service.EmqStrategy;
import com.bbzn.device.client.service.GaodeMapApiService;
import com.bbzn.device.client.service.GroupDeviceService;
import com.bbzn.device.client.service.emq.order.impl.nb.NbSetWeatherImpl;
import com.bbzn.device.client.utils.Base64Util;
import com.bbzn.device.client.utils.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @Author: wulongbo
 * @Date : 2021/4/9 11:19
 * @Version 1.0
 */
@Slf4j
@Component
public class EmqWeatherStrategy implements EmqStrategy {

    @Autowired
    private NbSetWeatherImpl nbSetWeather;

    @Autowired
    GaodeMapApiService gaodeMapApiService;


    @Autowired
    private GroupDeviceService groupDeviceService;

    // NB设备主动获取天气信息
    @Override
    public String emqAction(String payLoad) {
        try {
            GpsResult result = JSON.parseObject(payLoad, GpsResult.class);
            if (null == result || StringUtils.isEmpty(result.getImei())) {
                return "json解析错误";
            }
            if (CollectionUtils.isEmpty(result.getWifis())) {
                return "json解析错误";
            }
            log.info("进入WIFI定位解析");
            GetPositionRequest request = new GetPositionRequest();
            request.setImei(result.getImei());
            request.setOutput("json");
            request.setAccesstype(1);
            String macInfo = result.getWifis().stream().map(this::getMacInfo).filter(Objects::nonNull).collect(Collectors.joining("|", "", ""));
            request.setMacs(macInfo);
            request.setMmac(macInfo);
            ResultResponse<GetPositionResult> response = gaodeMapApiService.getPosition(request);
            if (null == response.getData() ||
                    StringUtils.isEmpty(response.getData().getResult().getAdcode())) {
                return "WIFI定位解析失败";
            }
            String adcode = response.getData().getResult().getAdcode();
            log.info("WIFI定位请求城市编码：" + adcode);
            GetWeatherInfoRequest weatherRequest = new GetWeatherInfoRequest();
            weatherRequest.setOutput("json");
            weatherRequest.setCity(adcode);
            weatherRequest.setExtensions("base");
            ResultResponse<GetWeatherInfoResult> weather = gaodeMapApiService.getWeatherInfo(weatherRequest);
            if (null == weather.getData() ||
                    CollectionUtils.isEmpty(weather.getData().getLives())) {
                return "获取天气失败";
            }
            LiveInfo liveInfo = weather.getData().getLives().get(0);
            Map map = new HashMap<>();
            map.put("code", "3018");
            map.put("area", Base64Util.decode(liveInfo.getProvince() + liveInfo.getCity()));
            map.put("temperature", liveInfo.getTemperature());
            log.info(DateUtil.getCurrentTime());
            map.put("time", DateUtil.getCurrentTime());
            map.put("imei", result.getImei());
            map.put("weather", Base64Util.decode(liveInfo.getWeather()));
            ProductUnionDTO productUnionDTO = groupDeviceService.getDeviceDetailByImei(result.getImei());
            productUnionDTO.setUserName("设备主动请求天气");
            nbSetWeather.sendOrder(map, productUnionDTO, "CN");
        } catch (Exception e) {
            e.printStackTrace();
            return "WIFI定位失败！";
        }
        return JSON.toJSONString(payLoad);
    }

    private String getMacInfo(WifiPosition position) {
        if (null == position || StringUtils.isEmpty(position.getMac())
                || StringUtils.isEmpty(position.getSignal()) || StringUtils.isEmpty(position.getSsid())) {
            return null;
        }
        StringBuilder macStr = new StringBuilder(position.getMac());
        macStr.append(",");
        macStr.append(position.getSignal());
        macStr.append(",");
        macStr.append(position.getSsid());
        return macStr.toString();
    }
}
